package com.ybc.future;

import java.util.concurrent.Callable;

//自己手写的 Future类 就写死了
//主要是存了一个callable 然后执行完成 改state   根据state来阻塞获取

public class MyFuture implements Runnable{

    private Callable callable;


    private volatile Object result;

    //0 未完成 1 完成
    private volatile int state;

    public MyFuture(Callable callable) {
        this.callable = callable;
    }

    public synchronized Object get() throws Exception {
        //避免虚假唤醒
        while (state == 0) {
            this.wait();
        }
        return result;
    }


    //运行完唤醒其他的即可  若他先 则能唤醒  若他后 则他不会阻塞
    public synchronized void run() {
        try {
            if (callable == null){
                throw new Exception("callable is null");
            }
            if(state == 1){
                return;
            }
            result = callable.call();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        state = 1;
        this.notifyAll();

    }

}
